package com.caiyouxi.goods.service;

import com.caiyouxi.common.bean.QueryParams;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.finance.service.FinancePaymentDetailService;
import com.caiyouxi.goods.mapper.GoodsDiscountMapper;
import com.caiyouxi.goods.model.GoodsDiscount;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.order.model.OrderBean;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/11/9.
 */
@Service
public class GoodsDiscountsService extends BaseService {

    private Logger logger = Logger.getLogger(GoodsDiscountsService.class);

    @Autowired
    private GoodsDiscountMapper goodsDiscountMapper;
    @Autowired
    private FinancePaymentDetailService financePaymentDetailService;

    /**
     * 查询商品折扣设置
     */
    public ResData get_goods_discounts_info(GoodsDiscount goodsDiscount){
        GoodsDiscount newGoodsDiscount = get_goods_discount(goodsDiscount.getId());
        return  success(newGoodsDiscount);
    }


    public GoodsDiscount get_goods_discount(Integer discount_id){
        String redis_key = "GOODS_DISCOUNT_"+ discount_id;
        logger.info("search redis...");
        GoodsDiscount newGoodsDiscount = (GoodsDiscount) redisService.get(redis_key);
        if (null == newGoodsDiscount){
            logger.info("search db...");
            newGoodsDiscount  = goodsDiscountMapper.get_goods_discounts_info(discount_id);
            redisService.set(redis_key,newGoodsDiscount);
        }
        return newGoodsDiscount;
    }

    /**
     * 查询商品折扣设置列表
     */
    public ResData get_goods_discounts_list(GoodsDiscount goodsDiscount){
        Integer reids_page_size = Integer.parseInt( redisService.get("sys.pagesize").toString());
        if(null != reids_page_size){
            goodsDiscount.setPage_size(reids_page_size);
        }
        List<GoodsDiscount> goodsDiscounts = goodsDiscountMapper.get_goods_discounts_list(goodsDiscount);
        int total = goodsDiscountMapper.get_goods_discounts_list_count(goodsDiscount);
        QueryParams pageList = new QueryParams();
        pageList.setTotal(total);
        pageList.setPage(goodsDiscount.getPage());
        pageList.setPage_size(goodsDiscount.getPage_size());
        pageList.setList(goodsDiscounts);
        return success(pageList);
    }

    /**
     * 新增商品折扣设置
     */
    @Transactional
    public ResData add_goods_discounts(GoodsDiscount goodsDiscount){
        int result =goodsDiscountMapper.add_goods_discounts(goodsDiscount);
        if(result == 1){
            return success(null);
        }
        return failed(ErrorCode.SYS_GOOdSDISCOUTS_ADD_ERROR.getCode(),ErrorCode.SYS_GOOdSDISCOUTS_ADD_ERROR.getMsg(),null);
    }

    /**
     * 修改商品折扣设置
     */
    @Transactional
    public ResData update_goods_discounts(GoodsDiscount goodsDiscount){
        int result = goodsDiscountMapper.update_goods_discounts(goodsDiscount);
        if(result == 1){
            String redis_key = "GOODS_DISCOUNT_"+goodsDiscount.getId();
            redisService.set(redis_key,goodsDiscount);  //更新缓存内容
            return success(null);
        }
        return failed(ErrorCode.SYS_GOOdSDISCOUTS_UPDATE_ERROR.getCode(),ErrorCode.SYS_GOOdSDISCOUTS_UPDATE_ERROR.getMsg(),null);
    }

    /**
     * 删除商品折扣设置
     */
    @Transactional
    public ResData delete_goods_discounts(GoodsDiscount goodsDiscount){
        int result =goodsDiscountMapper.delete_goods_discounts(goodsDiscount);
        if(result == 1){
            String redis_key = "GOODS_DISCOUNT_"+goodsDiscount.getId();
            redisService.remove(redis_key);  //删除缓存
            return success(null);
        }
        return failed(ErrorCode.SYS_GOOdSDISCOUTS_DELTET_ERROR.getCode(),ErrorCode.SYS_GOOdSDISCOUTS_DELTET_ERROR.getMsg(),null);
    }

    /**
     * 查询有效期内target_type类型折扣，对象编号target_id
     */
    public List<GoodsDiscount> goods_discounts_usefull_list(String target_type,String target_id){
        HashMap<String, Object> map = new HashMap();
        map.put("target_type",target_type);
        map.put("target_id",target_id);
        map.put("now_time",new Date());
        return goodsDiscountMapper.goods_discounts_usefull_list(map);
    }

    /**
     * 获取商品折扣信息
     */
    public GoodsDiscount get_goods_discounts(GoodsInfo gInfo){
        //先查询有效的折扣信息，根据target_type、target_id
        HashMap<String,Object> map = new HashMap();
        map.put("target_type","GOODS");
        map.put("target_id",gInfo.getId());
        map.put("now_time",new Date());
        GoodsDiscount goodsDiscount = goodsDiscountMapper.check_goods_discounts_amount(map);
        if(goodsDiscount == null){
            map.put("target_type","CATEGORY");
            map.put("target_id",gInfo.getCategory_id());
            goodsDiscount = goodsDiscountMapper.check_goods_discounts_amount(map);
        }
        return goodsDiscount;
    }


    /**
     * 校验商品折扣限制条件
     */
    public boolean check_goods_discount_num(String max_per_goods,Integer num){
        if(!"0".equals(max_per_goods)){
            //检查订单商品总数量是否大于等于max_per_goods
            if(num >= Integer.valueOf(max_per_goods)){
                return false;//超出商品购买数量的限制，不能享受折扣
            }
        }
        return true;
    }

    /**
     * 检验订单折扣限制
     */
    public boolean check_order_discount_num(String max_order,String duration,Integer discount_id){
        if(!"0".equals(max_order)){
            //获取满足条件的折扣信息记录 //当前时间到最早的一笔订单时间间隔分钟
            OrderBean order = financePaymentDetailService.get_min_by_payment_type_and_payment_detail("GOODS_DISCOUNT",discount_id);//折扣类型GOODS_DISCOUNT
            if(order != null){
                //存在第一笔订单
                Date first_time = order.getCreate_time();
                //判断当前时间到第一笔时间的间隔（分钟）是否大于等于duration
                Long jiange = (new Date().getTime() - first_time.getTime()) / (1000 * 60);
                if(jiange >= Long.valueOf(duration)){
                    //d大于等于duration，说明已超过折扣时间范围
                    //不享受折扣
                    return false;
                }else{
                    //获取满足条件的订单总数
                    Integer sum = financePaymentDetailService.get_sum_by_payment_type_and_payment_detail("GOODS_DISCOUNT",discount_id);
                    if(sum >= Integer.valueOf(max_order)){
                        //说明已超出限制的订单数量，不享受折扣优惠
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     *检验折扣优惠信息
     */
    public List<GoodsDiscount> check_goods_discounts(String target_type, String target_id){
        //查询当前可用的有效期内的折扣信息，针对具体的target_type、target_id
        return goods_discounts_usefull_list(target_type,target_id);
    }

    /**
     * 查询有效期内该商品及该商品品类的券
     */
    public List<GoodsDiscount> get_goods_discounts_usefull_list(GoodsInfo gInfo){
        HashMap<String, Object> map = new HashMap();
        map.put("target_type","GOODS");
        map.put("target_id",gInfo.getId());
        map.put("now_time",new Date());
        //查询商品的券
        List<GoodsDiscount> goods_discounts = goodsDiscountMapper.goods_discounts_usefull_list(map);
        map.put("target_type","GOODS_CATEGORY");
        map.put("target_id",gInfo.getCategory_id());
        //查询该商品品类的券
        if(gInfo.getCategory_id() != null && !"".equals(gInfo.getCategory_id())){
            List<GoodsDiscount> goods_discounts1 = goodsDiscountMapper.goods_discounts_usefull_list(map);
            goods_discounts.addAll(goods_discounts1);
        }
        return goods_discounts;
    }
}
